
import os
from dify_client.client import ChatClient,WorkflowClient,DifyClient
import json

class DifyHelper:
    def __init__(self,dify_base_url:str,api_key:str):
        self.dify_base_url = dify_base_url
        self.api_key = api_key
        print(self.dify_base_url)
        # self.dify_client = DifyClient(api_key,base_url=dify_base_url)
        self.chat_client = ChatClient(api_key,base_url=dify_base_url)
        self.workflow_client = WorkflowClient(api_key,base_url=dify_base_url)
        self.dify_client = DifyClient(api_key,base_url=dify_base_url)

    def send_workflow(self,paramters:dict) -> dict:
        wf_response = self.workflow_client.run(inputs=paramters,response_mode="blocking", user="dify_batch_runner")
        wf_response.raise_for_status()

        result = wf_response.json()

        return result['data']['outputs']

    def send_txt_message(self,message:str):
        chat_response = self.chat_client.create_chat_message(inputs={"query": message},query="",
                                                                  response_mode="blocking", user="dify_batch_runner")
        chat_response.raise_for_status()

        result = chat_response.json()

        print(result.get('answer'))

    def send_json_message(self,paramters:dict,query:str):
        chat_response = self.chat_client.create_chat_message(inputs=paramters,query=query,
                                                                  response_mode="blocking", user="dify_batch_runner")
        chat_response.raise_for_status()

        result = chat_response.json()

        # print(result.get('answer'))
        return result.get('answer')
    
    def send_json_message_get_json_result(self,paramters:dict,query:str):
        chat_response = self.chat_client.create_chat_message(inputs=paramters,query=query,
                                                                  response_mode="blocking", user="dify_batch_runner")
        chat_response.raise_for_status()

        result = chat_response.json()

        # print(result.get('answer'))
        answer_str = result.get('answer')
        # print(answer_str)
        answer = answer_str.replace('```json','').replace("```",'')
        return answer


    def upload_file(self,file):
        d_response = self.dify_client.file_upload('zyy',file)
        d_response.raise_for_status()

        result = d_response.json()
        return result['id']



